package com.pr.threadpool;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @projectName:spring-skill
 * @see:com.pr.threadpool
 * @author:LXC
 * @createTime:2024/7/30 11:01
 * @version:1.0
 */
public class ThreadUnsafeExample {
    private Integer cnt = 0;

    private AtomicInteger integer;

    private Object obj = new Object();

    ReentrantLock reentrantLock = new ReentrantLock();

    /**
     * 通过reentranlock实现线程安全
     */
    public void add() {
        reentrantLock.lock();

        try {
            cnt++;
        } finally {
            reentrantLock.unlock();
        }
    }

    /**
     * 通过synchronized实现线程安全
     */
    synchronized public void add1() {
        cnt++;
    }

    /**
     * 通过synchornized锁住对象实现线程安全
     */
    public void add4(){
        synchronized (obj){
            cnt++;
        }
    }

    /**
     * 描述:通过原子类实现线程安全
     */
    public void add3() {
        integer.getAndIncrement();
    }

    public int get() {
        return cnt;
    }
}
